package com.malou.client.ventas.proveedor;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.binding.FieldBinding;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.Status;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.form.HiddenField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.Validator;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.toolbar.FillToolItem;
import com.google.gwt.core.client.GWT;
import com.malou.client.MalouConstants;
import com.malou.client.util.ComboboxFieldBinding;
import com.malou.client.util.Utilities;

public class ProveedorDialog extends Dialog {

	protected HiddenField<String> id;
	protected TextField<String> razonsocial;
	protected TextField<String> representantelegal;
	protected TextField<String> ruc;
	protected TextField<String> dni;
	protected TextField<String> telefono;
	protected TextField<String> celular;
	protected TextField<String> direccion;
	protected TextField<String> email;
	protected TextField<String> descripcion;
	private ComboBox<BeanModel> tipo;
	protected Button cancelar;
	protected Button guardar;
	protected Status status;

	private FormBinding formBindings;
	private FormPanel panel;
	
	private MalouConstants constants = GWT.create(MalouConstants.class);

	public ProveedorDialog() {
super();
		setModal(true);
		setButtonAlign(HorizontalAlignment.LEFT);
		setButtons("");
		setResizable(false);
		setSize(450, 355);
		
		panel = new FormPanel();
		panel.setBorders(false);
		panel.setBodyBorder(false);
		panel.setPadding(5);
		panel.setHeaderVisible(false);
		panel.setLabelWidth(110);

		formBindings = new FormBinding(panel, false);
		addFields();

				
		setFocusWidget(razonsocial);
		Component comp[] = { razonsocial, ruc, representantelegal, dni,
				telefono, celular, direccion, email, descripcion, tipo, guardar };
		Utilities.Enter(comp);
	}

	@Override
	protected void createButtons() {
		super.createButtons();

		if (constants == null) {
			constants = GWT.create(MalouConstants.class);
		}
		
		status = new Status();
		status.setBusy(constants.guardando());
		status.hide();
		status.setAutoWidth(true);
		getButtonBar().add(status);

		getButtonBar().add(new FillToolItem());

		cancelar = new Button(constants.cancelar(),
				IconHelper.createPath("images/icons/cancel.png"));
		cancelar.setSize(70, 25);

		cancelar.addSelectionListener(new SelectionListener<ButtonEvent>() {
			public void componentSelected(ButtonEvent ce) {
				ProveedorDialog.this.hide();
			}

		});

		guardar = new Button(constants.guardar(),
				IconHelper.createPath("images/icons/save_all.png"));
		guardar.setSize(70, 25);
guardar.addSelectionListener(new SelectionListener<ButtonEvent>() {
			public void componentSelected(ButtonEvent ce) {
				guardar();

			}
		});

		addButton(guardar);
		addButton(cancelar);

	}

	protected boolean validate() {
		boolean rs = razonsocial.isValid();
		boolean rl = representantelegal.isValid();
		boolean rc = ruc.isValid();
		boolean dn = dni.isValid();
		boolean tlf = telefono.isValid();
		boolean cel = celular.isValid();
		boolean dir = direccion.isValid();
		boolean ema = email.isValid();
		boolean desc = descripcion.isValid();
		boolean tip = tipo.isValid();

		return rs && rl && rc && dn && tlf && cel && dir && ema && desc && tip;
	}

	private void addFields() {

		id = new HiddenField<String>();
		id.setVisible(false);
		panel.add(id);

		razonsocial = new TextField<String>();
		razonsocial.setMinLength(3);
		razonsocial.setFieldLabel(constants.proveedorRazonSocial());
		razonsocial.setAllowBlank(false);

		representantelegal = new TextField<String>();
		representantelegal.setMinLength(4);
		representantelegal.setFieldLabel(constants
				.proveedorRepresentanteLegal());
		representantelegal.setAllowBlank(true);

		ruc = new TextField<String>();
		ruc.setMinLength(11);
		ruc.setMaxLength(11);
		Utilities.setDigitos(ruc, 11);
		ruc.setFieldLabel(constants.proveedorRuc());
		ruc.setAllowBlank(false);

		dni = new TextField<String>();
		dni.setMinLength(8);
		dni.setMaxLength(8);
		Utilities.setDigitos(dni, 8);
		dni.setFieldLabel(constants.proveedorDni());
		dni.setAllowBlank(true);// funcion que te permite vacios

		telefono = new TextField<String>();
		telefono.setMinLength(3);
		Utilities.setNumeric(telefono);
		telefono.setFieldLabel(constants.proveedorTelefono());

		celular = new TextField<String>();
		celular.setMinLength(3);
		Utilities.setNumeric(celular);
		celular.setFieldLabel(constants.proveedorCelular());

		direccion = new TextField<String>();
		direccion.setMinLength(3);
		direccion.setFieldLabel(constants.proveedorDireccion());

		email = new TextField<String>();
		email.setMinLength(3);
		email.setFieldLabel(constants.proveedorEmail());

		final String emailReg = "[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}";
		final String errMsg = constants.emailNoValido();
		email.setValidator(new Validator() {
			public String validate(Field<?> field, String value) {
				if (!value.toUpperCase().matches(emailReg))
					return errMsg;
				return null;
			}
		});

		descripcion = new TextField<String>();
		descripcion.setMinLength(3);
		descripcion.setFieldLabel(constants.proveedorDescripcion());

		Proveedores.getComboProveedores();
		Proveedores.loaderTipoProveedor.load();

		tipo = new ComboBox<BeanModel>();
		tipo.setEditable(false);
		tipo.setFieldLabel(constants.proveedorTipo());
		tipo.setDisplayField("descripcion");
		tipo.setEmptyText("Seleccione...");
		tipo.setWidth(150);
		tipo.setStore(Proveedores.storeTipoProveedor);
		tipo.setTypeAhead(true);
		tipo.setTriggerAction(TriggerAction.ALL);
		tipo.setValueField("descripcion");
		tipo.setAllowBlank(false);
		

		panel.add(setLayout(razonsocial, "95%", 90), new ColumnData(1));
		panel.add(setLayout(ruc, "50%", 90), new ColumnData(1));
		panel.add(setLayout(representantelegal, "95%", 90), new ColumnData(1));
		panel.add(setLayout(dni, "50%", 90), new ColumnData(1));
		panel.add(setLayout(telefono, "50%", 90), new ColumnData(1));
		panel.add(setLayout(celular, "50%", 90), new ColumnData(1));
		panel.add(setLayout(direccion, "95%", 90), new ColumnData(1));
		panel.add(setLayout(email, "95%", 90), new ColumnData(1));
		panel.add(setLayout(descripcion, "95%", 90), new ColumnData(1));
		panel.add(setLayout(tipo, "95%", 90), new ColumnData(1));
		
		add(panel);

	}

	public void reset() {
		setIconStyle("icon-new");
		setHeading(constants.proveedorNuevoProveedor());

		id.clear();
		razonsocial.clear();
		representantelegal.clear();
		ruc.clear();
		dni.clear();
		telefono.clear();
		celular.clear();
		direccion.clear();
		email.clear();
		descripcion.clear();
		status.hide();
		getButtonBar().enable();
	}

	public void setStore(ListStore<BeanModel> store) {
	
		formBindings.addFieldBinding(new FieldBinding(id, "id"));
		formBindings.addFieldBinding(new FieldBinding(razonsocial,
				"razonsocial"));
		formBindings.addFieldBinding(new FieldBinding(representantelegal,
				"representantelegal"));
		formBindings.addFieldBinding(new FieldBinding(ruc, "ruc"));
		formBindings.addFieldBinding(new FieldBinding(dni, "dni"));
		formBindings.addFieldBinding(new FieldBinding(telefono, "telefono"));
		formBindings.addFieldBinding(new FieldBinding(celular, "celular"));
		formBindings.addFieldBinding(new FieldBinding(direccion, "direccion"));
		formBindings.addFieldBinding(new FieldBinding(email, "email"));
		formBindings.addFieldBinding(new FieldBinding(descripcion,
				"descripcion"));
		formBindings.addFieldBinding(new ComboboxFieldBinding(tipo, "tipo"));
		formBindings.setStore(store);
	}

	public void beforeEdit() {
		setIconStyle("icon-update");
		setHeading(constants.proveedorModificarProveedor());

		status.hide();
		getButtonBar().enable();
	}

	public void bind(BeanModel selectedModel) {
		formBindings.bind(selectedModel);
	}

	public void unbind() {
		formBindings.unbind();
	}

	private LayoutContainer setLayout(Component comp, String porcentaje,
			Integer withlabel) {
		LayoutContainer layout = new LayoutContainer();
		FormLayout fl = new FormLayout(LabelAlign.LEFT);
		fl.setLabelWidth(withlabel);
		layout.setLayout(fl);
		layout.add(comp, new FormData(porcentaje));

		return layout;
	}

	private void guardar() {
		if (validate()) {
			status.show();
			getButtonBar().disable();

			Proveedor prv = new Proveedor();
			if (id.getValue() != null)
				prv.setId(Integer.valueOf(id.getValue()));
			prv.setRazonsocial(razonsocial.getValue());
			prv.setRepresentantelegal(representantelegal.getValue());
			prv.setRuc(ruc.getValue());
			prv.setDni(dni.getValue());
			prv.setTelefono(telefono.getValue());
			prv.setCelular(celular.getValue());
			prv.setDireccion(direccion.getValue());
			prv.setEmail(email.getValue());
			prv.setDescripcion(descripcion.getValue());
			if (tipo.getValue().get("id") != null)
				prv.setTipoproveedor_id(Integer.parseInt(tipo.getValue()
						.get("id").toString()));

			Proveedores.proveedorDialog = ProveedorDialog.this;
			Proveedores.save(prv);
		}

	}

}